﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace PhoneApp1
{
    public partial class PhonePage2 : PhoneApplicationPage
    {

        public PhonePage2()
        {
            InitializeComponent();
        }

        private void DisplayMessage(string message, string caption)
        {
            this.Dispatcher.BeginInvoke(
                    delegate
                    {
                        MessageBox.Show(message, caption, MessageBoxButton.OK);
                    });
        }

        private void addChoice_Click(object sender, RoutedEventArgs e)
        {
            if (choiceBox.Text == "")
            {
                DisplayMessage("You need choice text filled in.", "Error");
                return;
            }
            Choice c = new Choice();
            c.choiceText = choiceBox.Text;
            //p.choices.Add(c);
            choicesList.Items.Add(c);
        }

        private void removeChoice_Click(object sender, RoutedEventArgs e)
        {
            if (choicesList.SelectedIndex == -1)
            {
                DisplayMessage("Select a choice first.", "Error");
                return;
            }
            choicesList.Items.RemoveAt(choicesList.SelectedIndex);
        }

        private void Createpoll_Click(object sender, RoutedEventArgs e)
        {
            if (choicesList.Items.Count < 2)
            {
                DisplayMessage("You need at least 2 choices.", "Error");
                return;
            }
            if (pollName.Text == "")
            {
                DisplayMessage("You need a poll name.", "Error");
                return;
            }
            if (pollQuestion.Text == "")
            {
                DisplayMessage("You need a question.", "Error");
                return;
            }
            Poll p = new Poll();
            foreach (Choice c in choicesList.Items)
            {
                p.choices.Add(c);
            }
            p.pollName = pollName.Text;
            p.questionText = pollQuestion.Text;
            p.creator = (App.Current as App).fileStorage.df.login;
            (App.Current as App).fileStorage.df.polls.Add(p);

            PollAppMessage m = new PollAppMessage();
            m.sender = (App.Current as App).fileStorage.df.login;
            m.type = PollAppMessageType.newPoll;
            m.data = p.getBytes();
            ((App)App.Current).RelayContext.SendPollAppMessage(m);

            NavigationService.GoBack();
        }
    }
}
